package com.sky.cqculture.service.impl;

import com.sky.cqculture.Mapper.ProductMapper;
import com.sky.cqculture.Mapper.ShoppingCartMapper;
import com.sky.cqculture.pojo.Product;
import com.sky.cqculture.pojo.ShoppingCart;
import com.sky.cqculture.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    
    @Autowired
    private ProductMapper productMapper;
    
    @Override
    public ShoppingCart addToCart(Integer userId, Integer productId, Integer quantity) {
        // 检查购物车中是否已存在该商品
        ShoppingCart existingCartItem = shoppingCartMapper.findByUserIdAndProductId(userId, productId);
        
        if (existingCartItem != null) {
            // 如果存在，更新数量
            existingCartItem.setQuantity(existingCartItem.getQuantity() + quantity);
            shoppingCartMapper.updateQuantity(existingCartItem);
            return existingCartItem;
        } else {
            // 如果不存在，添加新商品
            ShoppingCart shoppingCart = new ShoppingCart(userId, productId, quantity);
            shoppingCartMapper.add(shoppingCart);
            return shoppingCart;
        }
    }
    
    @Override
    public List<ShoppingCart> getCartItems(Integer userId) {
        List<ShoppingCart> cartItems = shoppingCartMapper.findByUserId(userId);
        
        // 为每个购物车商品加载商品详情
        for (ShoppingCart cartItem : cartItems) {
            Product product = productMapper.findById(cartItem.getProductId());
            cartItem.setProduct(product);
        }
        
        return cartItems;
    }
    
    @Override
    public ShoppingCart updateCartItemQuantity(Integer userId, Integer productId, Integer quantity) {
        ShoppingCart cartItem = shoppingCartMapper.findByUserIdAndProductId(userId, productId);
        
        if (cartItem != null) {
            cartItem.setQuantity(quantity);
            shoppingCartMapper.updateQuantity(cartItem);
        }
        
        return cartItem;
    }
    
    @Override
    public void removeCartItem(Integer userId, Integer cartId) {
        // 先验证购物车项是否属于当前用户
        ShoppingCart cartItem = shoppingCartMapper.findByUserIdAndProductId(userId, cartId);
        if (cartItem != null) {
            shoppingCartMapper.deleteById(cartId);
        }
    }
    
    @Override
    public void clearCart(Integer userId) {
        shoppingCartMapper.clear(userId);
    }
}